package cn.wangkai.peanut.db;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.wangkai.peanut.db.iface.IDb;
import cn.wangkai.peanut.db.mod.GeneratedKey;
import cn.wangkai.peanut.db.util.ManagerException;



public class ManagerUtil {

	private static final Log log = LogFactory.getLog(ManagerUtil.class);
	
	public ManagerUtil() {
	}
	
	/**
	 * 判断字符是否是主键
	 * @param keywords
	 * @param fieldname
	 * @return
	 */
	private static boolean equalsIgnoreCaseKeyWord(String[] keywords,String fieldname){
		for (int i = 0; i < keywords.length; i++) {
			String keyword = keywords[i];
			if(StringUtils.equalsIgnoreCase(keyword,fieldname)) return true;
		}
		return false;
	}
	
	/**
	 * 获取类名称,不含路径
	 * @param c
	 * @return
	 */
	private static String getClassName(Class<?> c){
		Field[] fields=c.getDeclaredFields(); 

		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			try {
				if(StringUtils.equalsIgnoreCase(field.getName(),"TABLENAME")&&field.getModifiers()==25){
					return String.valueOf(field.get(c.newInstance()));
				}
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			} catch (InstantiationException e) {
			}
		}
		return c.getName().replaceAll(c.getPackage().getName()+".", "");
	}
	
	
	private static String[] getClassPrimaryKeys(Class<?> c){

		Field[] fields=c.getDeclaredFields(); 

		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			try {
				if(StringUtils.equalsIgnoreCase(field.getName(),"PRIMARYKEY")&&field.getModifiers()==25){
					return new String[]{String.valueOf(field.get(c.newInstance()))};
				}else if(StringUtils.equalsIgnoreCase(field.getName(),"PRIMARYKEYS")&&field.getModifiers()==25){
					return (String[]) field.get(c.newInstance());
				}
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			} catch (InstantiationException e) {
			}
		}
		return null;
	}
	
	/**
	 * 得到是否自增长
	 * @param c
	 * @return
	 */
	private static boolean getClassKeywordAuto(Class<?> c){

		Field[] fields=c.getDeclaredFields(); 

		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			try {
				if(StringUtils.equalsIgnoreCase(field.getName(),"KEYWORDAUTO")&&field.getModifiers()==25){
					return field.getBoolean(c.newInstance());
				}
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			} catch (InstantiationException e) {
			}
		}
		return false;
	}

	public static String InsertSQL(Object obj) throws ManagerException{
		try{
			Class<?> c =obj.getClass();
			Field[] fields=c.getDeclaredFields(); 
			String fieldvalues = "";
			String fieldparam = "";
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				if(field.getModifiers()==2){
	//				if(equalsIgnoreCaseKeyWord(keywords, field.getName())&&!keywordauto) continue;
					Method method = getClassMethod(obj, field.getName());
					if(method.invoke(obj)!=null){
						if(StringUtils.isNotEmpty(fieldvalues)){
								fieldvalues += ",";
								fieldparam += ",";
							}
							fieldvalues += field.getName();
							fieldparam += "?";
					}
				}
			}
			
			return "INSERT INTO "+getClassName(c)+ " ("+fieldvalues+")values("+fieldparam+")";
		}catch (Exception e) {
			throw new ManagerException(e);
		}
	}
	
	public static String InsertSQL(Class<?> c){
		return InsertSQL(c, getClassPrimaryKeys(c.getClass()), getClassKeywordAuto(c.getClass()));
	}
	/**
	 * 获得插入语句
	 * INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
	 * @param c 对象
	 * @param keyword 主键名称
	 * @param keywordauto 是否自增
	 * @return
	 * @deprecated
	 */
	public static  String InsertSQL(Class<?> c,String keyword,boolean keywordauto){
		return InsertSQL(c, new String[]{keyword}, keywordauto);
	}

	/**
	 * 获得插入语句
	 * INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
	 * @param c 对象
	 * @param keyword 主键名称
	 * @param keywordauto 是否自增
	 * @return
	 */
	public static  String InsertSQL(Class<?> c,String keywords[],boolean keywordauto){
		Field[] fields=c.getDeclaredFields(); 
		String fieldvalues = "";
		String fieldparam = "";
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			if(field.getModifiers()==2){
				if(equalsIgnoreCaseKeyWord(keywords, field.getName())&&!keywordauto) continue;
					if(StringUtils.isNotEmpty(fieldvalues)){
						fieldvalues += ",";
						fieldparam += ",";
					}
					fieldvalues += field.getName();
					fieldparam += "?";
			}
		}
		
		return "INSERT INTO "+getClassName(c)+ " ("+fieldvalues+")values("+fieldparam+")";
	
	}
	
	/**
	 * 获得分页数据
	 * @param rownum 记录条数
	 * @param pagesize 每页记录条数
	 * @param pagenum 第几页
	 * @param Fromsql
	 * @param Orders
	 * @param Descs
	 * @param DbType
	 * @param Rowcount
	 * @return
	 */
	public static String getQuery(int rownum,int pagesize,int pagenum,String Fromsql,Object[] Orders,Object[] Descs,int DbType,long Rowcount){
		String orderby1 = "";
		String orderby2 ="";
		if(Orders!=null&&Descs!=null)
		for (int i = 0; i < Orders.length; i++) {
			String order = Orders[i]==null?null:((String)Orders[i]);
			boolean desc = Descs[i]==null?null:((Boolean)Descs[i]);
			if(StringUtils.isNotBlank(order)){
				if(StringUtils.isNotBlank(orderby1)){
					orderby1 = orderby1+",";
					orderby2 = orderby2+",";
				}
				orderby1 += order+" "+(desc?"desc":"asc")+" ";
				orderby2 += order+" "+(desc?"asc":"desc")+" ";
			}
		}
		log.debug("pagesize="+pagesize+":pagenum="+pagenum);
		if(DbType==IDb.DB_MYSQL){
			return "SELECT "+Fromsql+" "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+" LIMIT "+((pagenum-1)*pagesize)+", "+pagesize;
		}else if(DbType==IDb.DB_SQLSERVER2005){
			return "SELECT * FROM ( SELECT row_number()over(order by __tc__)__rn__,* FROM (SELECT top "+(pagesize*pagenum)+" 0 __tc__,"+Fromsql+" "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+") AS B)AS A WHERE __rn__>"+((pagenum-1)*pagesize)+"";
		}else if(DbType==IDb.DB_SQLSERVER){
			long p = pagesize;
			long maxrownum = pagesize*pagenum;
			if(maxrownum>Rowcount){
				p = (pagesize-(maxrownum-Rowcount));
			}
			if(p<=0)p=pagesize;
			
			return "select * from (select top "+pagesize+" * from (SELECT TOP "+p+" * FROM ( SELECT TOP "+maxrownum+" "+Fromsql+" "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+" ) as tempTable  "+(StringUtils.isBlank(orderby2)?"":" ORDER BY "+orderby2)+") as tmp) as tmp2 "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+" ";
		}else if(DbType==IDb.DB_DB2){
			return "SELECT * FROM ( SELECT B.*, ROWNUMBER() OVER() AS RN FROM (SELECT "+Fromsql+" "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+") AS B)AS A WHERE A.RN BETWEEN "+((pagenum-1)*pagesize)+" AND "+pagesize*pagenum;
		}else if(DbType==IDb.DB_ORACLE){
			return "SELECT * FROM (SELECT A.*, ROWNUM RN FROM (SELECT  "+Fromsql+" "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+") A WHERE ROWNUM <= "+(pagesize*pagenum)+" ) WHERE RN >= "+((pagenum-1)*pagesize);
		}else if(DbType==IDb.DB_INTPLE){
			return "SELECT A.* FROM(SELECT  "+Fromsql+" "+(StringUtils.isBlank(orderby1)?"":" ORDER BY "+orderby1)+") A WHERE ROWNUM BETWEEN "+(((pagenum-1)*pagesize+1))+" AND "+(pagesize*pagenum);
		}
		return null;
	}
	
	
	/**
	 * 新增对象数据
	 * 
	 * @param conn
	 * @param qr
	 * @param obj
	 * @param keyword
	 * @param keywordauto
	 * @return
	 * @throws ManagerException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 */
	public static int add(Connection conn,Object obj,String[] keyword,boolean keywordauto) throws ManagerException, SQLException{
		return add(conn,obj,InsertSQL(obj.getClass(), keyword, keywordauto));
	}

	public static int add(Connection conn,Object obj) throws ManagerException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, SQLException{
		return add(conn,obj,InsertSQL(obj.getClass(), getClassPrimaryKeys(obj.getClass()), getClassKeywordAuto(obj.getClass())));
	}

	/**
	 * 新增对象数据
	 * 
	 * @param conn
	 * @param qr
	 * @param obj
	 * @param sql
	 * @throws ManagerException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 */
	public static int add(Connection conn,Object obj,String sql) throws ManagerException, SQLException {
		int rows = 0;
		QueryRunner qr = new QueryRunner();
		Object[] objs = getInsertParames(obj,sql);
		log.info(getSqlMore(sql,objs));
		rows = qr.update(conn, sql,objs);
		return rows;
	}
	
	/**
	 * 新增数据获取主键
	 * 
	 * @param conn
	 * @param obj
	 * @param sql
	 * @param pmdKnownBroken
	 * @return
	 * @throws SQLException
	 * @throws ManagerException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static GeneratedKey addgetgeneratedkey(Connection conn,Object obj,String sql) throws ManagerException, SQLException {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		GeneratedKey key = new GeneratedKey();
		boolean pmdKnownBroken = false;
		log.info(sql);
		try {
			stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			Object[] objs = getInsertParames(obj,sql);
			log.info(getSqlMore(sql,objs));
			fillStatement(stmt, pmdKnownBroken, objs);
			key.setUpdateNum(stmt.executeUpdate());
			rs = stmt.getGeneratedKeys();
			if(rs.next()) key.setGeneratedKey(rs.getObject(1));
		} catch (SQLException e) {
			log.error("获取主键更新方法失败", e);
			throw e;
		} finally {
			DbUtils.close(rs);
			DbUtils.close(stmt);
		}
	
		return key;
	}

	/**
	 * Class<?>需要设置	
	 * public static final String PRIMARYKEY="Primarykey";
	 * public static final String[] PRIMARYKEYS=new String[]{"Primarykey1","Primarykey2"};
	 * public static final String TABLENAME="TableName";
	 * 
	 * UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
	 * @param c
	 * @return
	 */
	public static  String UpdateSQL(Class<?> c){
		return UpdateSQL(c, getClassPrimaryKeys(c));
	}

	/**
	 * 
	 * UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
	 * @param c
	 * @param keyword
	 * @return
	 * @deprecated
	 */
	public static  String UpdateSQL(Class<?> c,String keyword){
		return UpdateSQL(c, new String[]{keyword});
	}

	/**
	 * UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
	 * @param c
	 * @param keywords
	 * @return
	 */
	public static  String UpdateSQL(Class<?> c,String[] keywords){
		if(keywords==null){
			keywords=getClassPrimaryKeys(c);
		}
		Field[] fields=c.getDeclaredFields(); 
		String fieldvalues = "";
		String keyfieldvalues = "";
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			log.debug(field.getName()+":"+field.getModifiers());
			if(field.getModifiers()==2){
				if(equalsIgnoreCaseKeyWord(keywords, field.getName())){
					if(StringUtils.isNotEmpty(keyfieldvalues)){
						keyfieldvalues += " AND ";
					}
					keyfieldvalues += field.getName()+"=?";
				}else {
					if(StringUtils.isNotEmpty(fieldvalues)){
						fieldvalues += ",";
					}
					fieldvalues += field.getName()+"=?";
				}
			}
		}
		return "UPDATE "+getClassName(c) + " SET "+fieldvalues+" WHERE "+keyfieldvalues+" ";
	}

	public static int update(Connection conn,Object obj) throws ManagerException{
		return update(conn,obj,UpdateSQL(obj.getClass(),getClassPrimaryKeys(obj.getClass())));
	}
	
	/**
	 * 更新对象数据
	 * 
	 * @param conn
	 * @param qr
	 * @param obj
	 * @param keyword
	 * @return
	 * @throws ManagerException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 */
	public static int update(Connection conn,Object obj,String[] keyword) throws ManagerException{
		return update(conn,obj,UpdateSQL(obj.getClass(), keyword));
	}
	
	/**
	 * 更新对象数据
	 * 
	 * @param conn
	 * @param qr
	 * @param obj
	 * @param sql
	 * @throws ManagerException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 */
	public static int update(Connection conn,Object obj,String sql) throws ManagerException {
		int rows = 0;
		try{
//		String regex = "update[ ]*[^ ]*[ ]*set[ ]*(.*)[ ]*where[ ]*(.*)[ ]*";
//		String[] regexs = StringParser.getAllGroups(regex,sql);
//		if(regexs==null||regexs.length!=2) throw new ManagerException("Update SQL语句不正确 \n正确：UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值\nSQL "+sql);
//		String[] parames = (regexs[0]+","+regexs[1]).split(",");
		Object[] objs = getSQLParames(obj, sql);
		QueryRunner qr = new QueryRunner();
		log.info(getSqlMore(sql,objs));
		rows= qr.update(conn, sql, objs);
		}catch (Exception e) {
			throw new ManagerException(e);
		}
		return rows;
	}
	
	public static  String DeleteSQL(Class<?> c){
		return DeleteSQL(c, getClassPrimaryKeys(c));
	}

	/**
	 * 
	 * @param c
	 * @param keyword
	 * @return
	 * @deprecated
	 */
	public static  String DeleteSQL(Class<?> c,String keyword){
		return DeleteSQL(c, new String[]{keyword});
	}

	/**
	 * DELETE FROM 表名称 WHERE 列名称 = 值
	 * @param c
	 * @param keywords
	 * @return
	 */
	public static  String DeleteSQL(Class<?> c,String[] keywords){
		if(keywords==null){
			keywords = getClassPrimaryKeys(c);
		}
		String keyfieldvalues = "";
		for (int i = 0; i < keywords.length; i++) {
			if(StringUtils.isNotEmpty(keyfieldvalues)){
				keyfieldvalues += " AND ";
			}
			keyfieldvalues +=  keywords[i]+"=?";
		}
		return "DELETE FROM "+getClassName(c) + " WHERE "+keyfieldvalues+" ";
	}

	/**
	 * 删除某个对象
	 * @param conn
	 * @param obj
	 * @param sql
	 * @return
	 * @throws ManagerException 
	 * @throws SQLException
	 */
	public static int delete(Connection conn,Object obj,String sql) throws ManagerException, SQLException{
		int rows = 0;
		Object[] objs = getSQLParames(obj, sql);
		QueryRunner qr = new QueryRunner();
		log.info(getSqlMore(sql,objs));
		rows= qr.update(conn, sql, objs);
		return rows;
	}
	
	/**
	 * 删除某个对象
	 * @param conn
	 * @param obj
	 * @param keywords
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 * @throws ManagerException 
	 */
	public static int delete(Connection conn,Object obj,String[] keywords) throws SQLException, ManagerException{
		String sql = DeleteSQL(obj.getClass(), keywords);
		return delete(conn, obj, sql);
	}
	
	public static int delete(Connection conn,Object obj) throws SQLException, ManagerException{
		String sql = DeleteSQL(obj.getClass(),getClassPrimaryKeys(obj.getClass()));
		return delete(conn, obj, sql);
	}
	
	/**
	 * 得到SQL的参数名称
	 * @param SQL
	 * @return
	 */
	private static String[] getsqlParames(String SQL){
		List<String[]> lists = StringParser.getAll(",?([^= ]*)[ ]*=[ ]*\\?", SQL);
		if(lists.size()<=0) return null;
		String[] parames = new String[lists.size()];
		int i = 0;
		for (String[] tmp : lists) {
			parames[i]=tmp[0];
			i++;			
		}
		return parames;
	}

	/**
	 * 获得插入参数的值
	 * @param obj
	 * @param sql
	 * @return
	 * @throws ManagerException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static Object[] getInsertParames(Object obj, String sql) throws ManagerException{
		try{
			String regex = "insert[ ]*into[ ]*[^\\(]*\\(([^\\)]*)\\)[ ]*values[ ]*[^\\(]*\\(([^\\)]*)\\)";
			String[] regexs = StringParser.getAllGroups(regex,sql);
			if(regexs==null||regexs.length!=2){
				throw new ManagerException("SQL语句不正确 \n正确：INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)\nSQL "+sql);
			}
			String[] parames = regexs[0].split(",");
			String[] values = regexs[1].split(",");
			if(parames.length!=values.length){
				throw new ManagerException("SQL左右参数不正确 \n正确：INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)\nSQL "+sql);
			}
			List<Object> lists = new ArrayList<Object>();
			for (int i = 0; i < parames.length; i++) {
				String parame = parames[i];
				Method method = getClassMethod(obj, parame);
				if(!StringUtils.equalsIgnoreCase("?", values[i])) continue;
				lists.add(method.invoke(obj));
				log.debug(parame+"-"+method.getReturnType().getName());
			}
			return lists==null?null:lists.toArray();
		}catch (Exception e) {
			throw new ManagerException(e);
		}
	}

	/**
	 * 根据SQL得到需要插入的对象
	 * @param obj
	 * @param sql
	 * @return
	 * @throws ManagerException 
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private static Object[] getSQLParames(Object obj,String sql) throws ManagerException {
		try{
			String[] parames = getsqlParames(sql);
			List<Object> lists = new ArrayList<Object>();
			for (int i = 0; i < parames.length; i++) {
				String parame = parames[i];
				if(StringUtils.isEmpty(parame)) continue;
				Method method = getClassMethod(obj, parame);
				lists.add(method.invoke(obj));
				log.debug(parame+"-"+method.getReturnType().getName()+"-"+method.invoke(obj));
			}
			return lists==null?null:lists.toArray();
		}catch (Exception e) {
			throw new ManagerException(e);
		}
	}

	/**
	 * 根据名称得到get方法对象
	 * @param obj
	 * @param filed
	 * @return
	 * @throws ManagerException 
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private static Method getClassMethod(Object obj,String filed) throws ManagerException{
		try{
			Method[] methods = obj.getClass().getMethods();
			for (int i = 0; i < methods.length; i++) {
				Method method = methods[i];
				if(StringUtils.equalsIgnoreCase("get"+filed,method.getName())){
					return method;
				}
			}
			return null;
		}catch (Exception e) {
			throw new ManagerException(e);
		}
	}
	
	/**
	 * 自动填充stmt的值
	 * 
	 * @param stmt
	 * @param pmdKnownBroken
	 * @param params
	 * @throws SQLException
	 */
	private static void fillStatement(PreparedStatement stmt, boolean pmdKnownBroken,
			Object[] params) throws SQLException {
	
		if (params == null) {
			return;
		}
	
		ParameterMetaData pmd = null;
		if (!pmdKnownBroken) {
			pmd = stmt.getParameterMetaData();
			if (pmd.getParameterCount() < params.length) {
				throw new SQLException("Too many parameters: expected "
						+ pmd.getParameterCount() + ", was given "
						+ params.length);
			}
		}
		for (int i = 0; i < params.length; i++) {
			if (params[i] != null) {
				stmt.setObject(i + 1, params[i]);
			} else {
				// VARCHAR works with many drivers regardless
				// of the actual column type. Oddly, NULL and
				// OTHER don't work with Oracle's drivers.
				int sqlType = Types.VARCHAR;
				if (!pmdKnownBroken) {
					try {
						sqlType = pmd.getParameterType(i + 1);
					} catch (SQLException e) {
						pmdKnownBroken = true;
					}
				}
				stmt.setNull(i + 1, sqlType);
			}
		}
	}

	
	/**
	 * 正则方法对象
	 * @author wangk
	 *
	 */
	private static class StringParser{
	    
	    /**
	     * If multi-groups contained in regex, all groups will be found out
	     * @param regex the regular expression
	     * @param original the original source
	     * @return the result in order as groups in regex
	     */
	    public static String[] getAllGroups(String regex, String original){
	        Matcher m = getMatcher(regex, original);
	        String[] result=new String[m.groupCount()];
	        if (m.find()) {
	        	for(int i=0;i<m.groupCount();i++){
	        		result[i] = new String(m.group(i+1));
	        	}
	            m = null;
	        }
	        return result;
	    }
	    /**
	     * If multi-groups contained in regex, all groups will be found out
	     * @param regex
	     *            the regular expression
	     * @param original
	     *            the original source
	     * @return the result in order as groups in regex
	     */
	    public static List<String[]> getAll(String regex, String original){
	    	List<String[]> list = new ArrayList<String[]>();
	        Matcher m = getMatcher(regex, original);
	        while (m.find()) {
	        	String[] result=new String[m.groupCount()];
	        	for(int i=0;i<m.groupCount();i++){
	        		result[i] = new String(m.group(i+1));
	        	}
	        	list.add(result);
	        }
	        return list;
	    }

	    
	    /**
	     * build one matcher for the regex. Will be used by more detail parse
	     * 
	     * @param regex the regular expression
	     * @param original the original source
	     * @return the matcher to do String Parser
	     */
	    public static Matcher getMatcher(String regex, String original) {
	        Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
	        Matcher m = p.matcher(original);
	        return m;
	    }
	}

	public static StringBuffer getSqlMore(String sql, Object[] params) {
		StringBuffer msg = new StringBuffer("");
		msg.append(" Query: ");
		msg.append(sql);
		msg.append(" Parameters: ");
	
		if (params == null) {
			msg.append("[]");
		} else {
			for (int i = 0; i < params.length; i++) {
				Object object = params[i];
				msg.append(object).append(",");
			}
		}
		return msg;
	}
}